package com.company;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @date : 2023-07-16 下午5:01
 */

public class P062_FreeLock {


    public static void main(String[] args) {

        SynchronizedClass synchronizedClass = new SynchronizedClass();
        for (int i = 0; i < 100; i++) {
            new Thread(synchronizedClass::method1).start();
        }
    }

    public static class SynchronizedClass {

        public static ReentrantLock lock = new ReentrantLock();
        public static Condition condition = lock.newCondition();


        public synchronized void method1() {
            // lock.lock();
            try {
                System.out.println("开始当前线程名:" + Thread.currentThread().getName());
                try {
                    condition.await();
                } catch (Exception e) {
                    // e.printStackTrace();
                }
                Thread.sleep(1000);
                System.out.println("结束当前线程名:" + Thread.currentThread().getName());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public void method2() {
            lock.lock();
            try {
                System.out.println("开始当前线程名:" + Thread.currentThread().getName());
                condition.signal();
                Thread.sleep(1000);
                System.out.println("结束当前线程名:" + Thread.currentThread().getName());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }


}
